package com.changhong.wlyspectrum.LoginActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.changhong.wlyspectrum.ForgetpsdActivity.ForgetpsdActivity;
import com.changhong.wlyspectrum.MainTestActivity.InfoInputActivity;
import com.changhong.wlyspectrum.MainTestActivity.MainTestActivity;
import com.changhong.wlyspectrum.NetWork.HttpMethods;
import com.changhong.wlyspectrum.NewDesign.HomeActivity;
import com.changhong.wlyspectrum.R;
import com.changhong.wlyspectrum.RegisterActivity.RegisterActivity;
import com.changhong.wlyspectrum.utils.ConnectDialog;
import com.changhong.wlyspectrum.utils.GlideCircleTransform;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * Created by Mr_tao
 * on 2017/3/6.
 */
public class LoginActivity extends Activity {
    private static final String TAG = "LoginActivity";
    private ImageView mLogoImg;
    private EditText mUserNameEdt;
    private EditText mPassWordEdt;
    private Button mForgetPwdBtn;
    private Button mRegBtn;
    private Button mLoginBtn;
    private String mUserName;
    private String mPassWord;
    private String mOwnUserName;
    private String mOwnPassWord;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_layout);

        InitUi();
    }

    private void InitUi(){
        mUserNameEdt = (EditText)findViewById(R.id.user_name);
        mUserNameEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    mUserNameEdt.setHint(null);
                }else{
                    if(mUserNameEdt.getText().length() != 0){
                        mUserNameEdt.setHint(null);
                    }else{
                        mUserNameEdt.setHint(R.string.input_user_name);
                    }
                }
            }
        });
        mUserNameEdt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(mUserNameEdt.getText().length() != 0){
                    mUserNameEdt.setHint(null);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mPassWordEdt = (EditText)findViewById(R.id.user_pwd);
        mPassWordEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    mPassWordEdt.setHint(null);
                }else{
                    if(mPassWordEdt.getText().length() != 0){
                        mPassWordEdt.setHint(null);
                    }else{
                        mPassWordEdt.setHint(R.string.input_pwd);
                    }
                }
            }
        });
        mPassWordEdt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(mPassWordEdt.getText().length() != 0){
                    mPassWordEdt.setHint(null);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mForgetPwdBtn = (Button)findViewById(R.id.forget_btn);
        mForgetPwdBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this,ForgetpsdActivity.class);
                startActivity(intent);
            }
        });

        mRegBtn = (Button)findViewById(R.id.reg_btn);
        mRegBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
            }
        });

        mLoginBtn = (Button)findViewById(R.id.login_btn);
        mLoginBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mUserName = mUserNameEdt.getText().toString();
                mPassWord = mPassWordEdt.getText().toString();
                if(!mUserName.isEmpty()){
                    if(!mPassWord.isEmpty()){
                        ConnectDialog.showDialog(LoginActivity.this,getString(R.string.is_login));
                        Login(mUserName,mPassWord);
                    }else{
                        Toast.makeText(getApplicationContext(),
                                R.string.input_pwd, Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(getApplicationContext(),
                            R.string.input_phone, Toast.LENGTH_SHORT).show();
                }
            }
        });

        mLogoImg = (ImageView)findViewById(R.id.my_img);
        //Glide.with(LoginActivity.this).load(R.drawable.tqls).transform(new GlideCircleTransform(LoginActivity.this)).into(mLogoImg);
    }

    private void InitData(){
        SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        mOwnUserName = myPref.getString("username", "");
        mOwnPassWord = myPref.getString("password", "");
        if((mOwnUserName != null) && (mOwnPassWord != null)){
            mUserNameEdt.setText(mOwnUserName);
            mPassWordEdt.setText(mOwnPassWord);
        }
    }

    private void Login(final String username,final String password){
        new Thread(){
            @Override
            public void run(){
                super.run();
                JSONObject js = new JSONObject();
                try {
                    js.put("phone", username);
                    js.put("password", password);
                    Response response = HttpMethods.GetResponse("/account/login",js.toString());
                    if(response.isSuccessful()){
                        String result = response.body().string();
                        Log.e(TAG,"result----->" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        Log.e(TAG,"code----->" + code);
                        if(code.compareTo("0") == 0) {
                            JSONObject jsonobj = jsonObject.getJSONObject("jsonObj");
                            String device_id = jsonobj.getString("device_id");
                            Log.e(TAG, "device_id----->" + device_id);
                            String user_id = jsonobj.getString("id");
                            Log.e(TAG, "user_id----->" + user_id);
                            String token = jsonobj.getString("token");
                            Log.e(TAG, "token----->" + token);
                            String phone = jsonobj.getString("phone");
                            SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                            SharedPreferences.Editor editor = mypref.edit();
                            editor.putString("username", username);
                            editor.putString("password", password);
                            editor.putString("device_id", device_id);
                            editor.putString("user_id", user_id);
                            editor.putString("token", token);
                            editor.putString("phone", phone);
                            editor.commit();
                            loginHandler.sendMessage(Message.obtain(loginHandler, 0));
                        }else{
                            loginHandler.sendMessage(Message.obtain(loginHandler, 1));
                        }
                    }else{
                        loginHandler.sendMessage(Message.obtain(loginHandler, 99));
                    }
                } catch (IOException e) {
                    loginHandler.sendMessage(Message.obtain(loginHandler, 99));
                    e.printStackTrace();
                } catch (JSONException e) {
                    loginHandler.sendMessage(Message.obtain(loginHandler, 99));
                    e.printStackTrace();
                }
            }
        }.start();
    }

    Handler loginHandler = new Handler(){
        public void handleMessage(android.os.Message msg){
            super.handleMessage(msg);
            ConnectDialog.dismiss();
            switch (msg.what) {
                case 0:
                    //Intent intent = new Intent(LoginActivity.this,MainTestActivity.class);
                    //Intent intent = new Intent(LoginActivity.this,InfoInputActivity.class);
                    //Intent intent = new Intent(LoginActivity.this,TestAnalyseActivity.class);  //for test
                    Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                    startActivity(intent);
                    break;
                case 1:
                    Toast.makeText(getApplicationContext(),
                            R.string.login_fail, Toast.LENGTH_LONG).show();
                    break;
                case 99:
                    Toast.makeText(getApplicationContext(),
                            R.string.network_error, Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        InitData();
    }
}
